package dao

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
	"simple-app/global"
	"simple-app/structs/tables"
)

var UserDao = new(userDao)

type userDao struct{}

func (r userDao) FindUserByAccount(account string) (m tables.User, err error) {
	if err = global.DB.Where(tables.User{Account: account}).Find(&m).Error; errors.Is(err, gorm.ErrRecordNotFound) {
		return m, fmt.Errorf("sys not exist")
	}
	return
}

func (r userDao) FindById(uid int64) (m tables.User, err error) {
	err = global.DB.Where(tables.User{UserId: uid}).First(&m).Error
	return
}

// CheckAccountIsExist 检查账户是否已经存在
func (r userDao) CheckAccountIsExist(account string) (bool, error) {
	var num int64
	err := global.DB.Model(&tables.User{}).Where(tables.User{Account: account}).Count(&num).Error
	if err != nil {
		return false, err
	}
	return num > 0, nil
}

func (r userDao) FindReferrerByReferCode(code string) (m tables.User, err error) {
	err = global.DB.Where(tables.User{InviteCode: code}).Find(&m).Error
	return
}

func (r userDao) CreateAccount(m *tables.User) error {
	return global.DB.Create(&m).Error
}
